# @File    : normal_ota.py
# @Project : Airtest_JBL_IOS

from common.connect import ConnectUtil
from common.operate import OperateUtil
from common.yamlUtil import YamlUtil
from airtest.core.api import *
from exception.custom_exception import ElectricException
from iOS.select_version import SelectVersion
import logging
from common.logUtil import info_i, warning_i
logging.getLogger("airtest").setLevel(logging.CRITICAL)


class NormalOta:

    def __init__(self, driver, poco):
        self.driver = driver
        self.poco = poco
        self.screen_size = self.poco.get_screen_size()
        # 获取屏幕宽和高
        self.width = self.screen_size[0]
        self.height = self.screen_size[1]

    # 读取存储的耳机版本号
    location = YamlUtil("data.yaml")
    h_version = location.read_yaml()['h_version']
    l_version = location.read_yaml()['l_version']
    s_h_version = location.read_yaml()['s_h_version']
    s_l_version = location.read_yaml()['s_l_version']
    test_device = location.read_yaml()['device']

    # ex = ExceptionUtil(poco)
    operate = OperateUtil()
    s = SelectVersion()
    c = ConnectUtil()

    earbud = "耳机：.*"
    case = "充电盒：.*"
    schedule = "剩余.*"
    a_version = "应用版本.*"
    process = ".*%"
    transmission = "正在传输.*"

    pass_num = 0
    fail_num = 0
    fail_list = []

    # 正常级流程
    def normal_ota(self, num):
        self.check_is_local_ota()
        version = self.check_version()
        for i in range(1, int(num)+1):
            try:
                start_time = time.time()
                for _ in range(2):
                    self.select_version(version, self.test_device)
                    self.ota_start(i, version)
                    self.ota_process(i, version)
                    if self.test_device == "耳机":
                        version = self.poco(nameMatches=f"{self.earbud}").get_name()[3:]
                    elif self.test_device == "充电盒":
                        version = self.poco(nameMatches=f"{self.case}").get_name()[4:]
                    sleep(1)
                end_time = time.time()
                total_time = end_time - start_time
                minutes, seconds = divmod(total_time, 60)
                info_i(f"第 {i} 次升级耗时: {int(minutes)} 分 {int(seconds)} 秒")
            except ElectricException:
                self.fail_num += 1
                self.fail_list.append(i)
                warning_i(f"第 {i} 次升级时耳机电量过低，无法升级!")
                break
            except TargetNotFoundError:
                self.fail_num += 1
                self.fail_list.append(i)
                warning_i("出现异常了，请手动跟换安装包或者出现运行程序")
                break
        sleep(2)
        info_i(f"测试完成, 共压测 {i} 次, 其中 PASS {self.pass_num} 次, FAIL {self.fail_num} 次, FAIL的轮数为{self.fail_list}")
        self.fail_list.clear()

    # 查看耳机版本号
    def check_version(self):
        other = self.poco("Others").wait(15)
        if other.exists():
            other.click()
            swipe((self.width * 0.5, self.height * 0.88), (self.width * 0.5, self.height * 0.6))
            self.poco("支持").click()
            if self.test_device == "耳机":
                version = self.poco(nameMatches=f"{self.earbud}").get_name()[3:]
                info_i(f"当前耳机版本为: {version}")
            else:
                version = self.poco(nameMatches=f"{self.case}").get_name()[4:]
                info_i(f"当前充电盒版本为: {version}")
            sleep(1)
            return version

    # 查看是否勾选本地下载
    def check_is_local_ota(self):
        other = self.poco("Others").wait(15)
        if other.exists():
            self.poco("com.back").click()
            self.poco("app menu").click()
            app_version = self.poco(nameMatches=f"{self.a_version}").attr("pos")
            pos_width = app_version[0]
            pos_height = app_version[1]
            touch((self.width * pos_width, self.height * pos_height), times=15)
            # 檢查local ota的複選框是否勾選，value == "1" 时，已勾选，
            check = self.poco("Local OTA upgrade checking").sibling("checkbox empty")
            if check.attr("value") == "1":
                pass
            else:
                check.click()
                check.refresh()
            self.poco("close white").click()
            self.poco("grey arrow back").click()
            (self.poco("Window").child("Other").child("Other").child("Other").child("Other")
             .child("Other").offspring("Table").child("Cell")[0].child("pro.tourpro2tws.black").click())

    # # 根据当前版本选择耳机升级版本
    def select_version(self, version, test_device):
        self.c.connect_windows()
        if version == self.h_version:
            self.s.select_version(f"{self.s_l_version}", test_device)
        elif version == self.l_version:
            self.s.select_version(f"{self.s_h_version}", test_device)
        self.c.connect_ios()

    def ota_start(self, i, version):
        if self.test_device == "耳机":
            self.poco("软件").click()
        else:
            self.poco("智能保护盒").click()
        self.poco("更新").refresh()
        self.poco("更新").click()
        if version == self.h_version:
            info_i(f"第 {i} 次降级开始...")
        elif version == self.l_version:
            info_i(f"第 {i} 次升级开始...")

    # 升级过程
    def ota_process(self, i, version):
        while True:
            if self.poco("耳机电量需超过 50%。").exists():
                raise ElectricException
            if not self.poco(nameMatches=f"{self.schedule}").exists():
                if self.poco("更新成功").exists():
                    self.poco("完成").click()
                    if self.test_device == "耳机":
                        version = self.poco(nameMatches=f"{self.earbud}").get_name()[3:]
                    else:
                        version = self.poco(nameMatches=f"{self.case}").get_name()[4:]
                    self.check_after_version(i, version)
                    break
                # 更新失败处理
                elif self.poco("更新失败").exists():
                    self.poco("取消").click()
                    sleep(2)
                    # version = self.ex.check_fail()
                    self.check_after_version(i, version)
                    self.fail_num += 1
                    self.fail_list.append(i)
                    break
                # general = self.poco(text="General").wait(20)
                # if general.exists():
                #     self.poco(text="Others").click()
                #     self.poco(text="支持").click()
                #     version = self.poco(textMatches=f"{self.earbud}").get_text()[4:]
                #     self.check_after_version(i, version)
                #     break
            if self.poco("重试").exists():
                self.poco("重试").click()
                sleep(1)
                self.poco("更新").click()

    # 根据升级后的版本来进行后续操作
    def check_after_version(self, i, version):
        if version == self.h_version:
            info_i(f"第 {i} 次升级成功...")
            sleep(1)
            info_i(f"第 {i} 次升级后的版本为: {version}")
            self.pass_num += 1
        elif version == self.l_version:
            # stop_app("jbl.stc.com.debug")
            # time.sleep(2)
            # start_app("jbl.stc.com.debug")
            # other = self.poco("Others").wait(30)
            # if other.exists():
            #     other.click()
            #     swipe((self.width * 0.5, self.height * 0.88), (self.width * 0.5, self.height * 0.6))
            #     self.poco("支持").click()
            #     version = self.poco(nameMatches=f"{self.earbud}").get_name()[4:]
            #     if version == self.l_version:
            info_i(f"第 {i} 次降级成功...")
            sleep(1)
            info_i(f"第 {i} 次降级后的版本为: {version}")

    # 获取进度条
    def check_process(self):
        pro = YamlUtil("process.txt")
        while True:
            if self.poco(nameMatches=f"{self.transmission}").exists():
                process = self.poco(nameMatches=f"{self.process}").get_name()[:-1]
                if process == "100%":
                    pro.clean_yaml()
                    pro.write_yaml(process)
                    break
                else:
                    pro.clean_yaml()
                    print(process)
                    pro.write_yaml(process)


